from PySide6.QtWidgets import QTabWidget, QWidget, QVBoxLayout, QHBoxLayout, QPushButton
from PySide6.QtCore import Qt, QSize
from PySide6.QtGui import QIcon
from terminal.ui import Terminal
from PySide6.QtWidgets import QLabel
import os

class TabManager(QTabWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setTabsClosable(True)  # 允许关闭标签页
        self.setMovable(True)  # 允许拖动标签页
        self.setElideMode(Qt.TextElideMode.ElideNone)  # 设置文本省略方式为None
        self.setUsesScrollButtons(True) # 启用滚动按钮
        self.tabCloseRequested.connect(self.close_tab)
        self.tab_counters = {}  # 用于记录标签页计数

        # 加载标签页图标
        self.tab_icon = QIcon(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'icons', 'computer-1.png'))
        

    def create_terminal_tab(self, session_name, session_data):
        """创建新的终端标签页"""
        # 处理重复的标签页名称
        base_name = session_name
        if base_name in self.tab_counters:
            self.tab_counters[base_name] += 1
            session_name = f"{base_name}({self.tab_counters[base_name]})"
        else:
            self.tab_counters[base_name] = 0
        
        # 创建标签页容器
        tab = QWidget()
        layout = QVBoxLayout(tab)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        
        # 创建新的终端实例
        terminal = Terminal()
        terminal.session_data = session_data
        layout.addWidget(terminal)
        
        # 添加新标签页
        index = self.addTab(tab, session_name)
        self.setTabIcon(index, self.tab_icon)
        self.setCurrentIndex(index)
        
        # 存储原始名称，用于关闭时更新计数器
        tab.base_name = base_name
        
        # 连接终端
        session_type = session_data['config']['session_type']
        params = session_data['config']['session_params']
        
        if session_type == '串口':
            terminal.connect_serial(params['port'], params['baudRate'], session_name)
        elif session_type == 'SSH':
            terminal.connect_ssh(params['host'], params['port'], params['username'], params['password'], session_name)
        elif session_type == 'Telnet':
            terminal.connect_telnet(params['host'], params['port'], session_name)
        
        return terminal
        
    def close_tab(self, index):
        """关闭标签页"""
        # 获取标签页中的终端实例
        tab = self.widget(index)
        terminal = tab.findChild(Terminal)
        
        # 断开终端连接
        if terminal:
            terminal.disconnect()
        
        # 更新标签页计数
        base_name = tab.base_name
        if base_name in self.tab_counters:
            # 检查是否还有其他同名标签页
            has_other_tabs = False
            for i in range(self.count()):
                if i != index and hasattr(self.widget(i), 'base_name') and self.widget(i).base_name == base_name:
                    has_other_tabs = True
                    break
            
            if not has_other_tabs:
                # 如果没有其他同名标签页，重置计数器
                del self.tab_counters[base_name]
        
        # 移除标签页
        self.removeTab(index)